package com.qikux.controller;


import cn.hutool.captcha.AbstractCaptcha;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.generator.MathGenerator;
import com.qikux.constraint.RssConst;
import org.haredot.annotation.Controller;
import org.haredot.annotation.RequestMapping;
import org.haredot.annotation.RequestParam;
import org.haredot.web.RequestMethod;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Random;

@Controller
@RequestMapping("/captcha")
public class CaptchaController {
    /**
     * 产生一个验证码
     */
    @RequestMapping(value = "/code", method = RequestMethod.GET)
    public void generatorCode(
            @RequestParam(value = "w", required = false, defaultValue = "140") Integer width ,
            @RequestParam(value = "h", required = false, defaultValue = "40") Integer height ,
            HttpSession session, HttpServletResponse response) throws Exception {
        // 用来 绘制一个 140 * 40 的 RGB的图片
        // 将 三种生成验证码的 方法进行封装
        String[] methods = {"createCircleCaptcha", "createLineCaptcha", "createShearCaptcha"} ;
        Class<CaptchaUtil> captchaUtilClass = CaptchaUtil.class;
        Random random = new Random();
        // 通过设置调用 methods 中对应的方法
        int index = random.nextInt(methods.length);
        // 获取 所及调用的 方法
        String methodName = methods[index] ;
        // 通过 反射 获取 methodName 对应的 method 对象
        Method method = captchaUtilClass.getMethod(methodName, int.class, int.class, int.class, int.class); 
        // 随机生成 5 ~ 20 个干扰线
        int count = random.nextInt(16) + 5 ;
        if ("createShearCaptcha".equals(methodName)) {
            count = 2 ;
        }
        // 通过 反射调用 method方法
        AbstractCaptcha captcha = (AbstractCaptcha)method.invoke(null, width, height, 4, count) ;

        if (Math.random() < 0.5) {
            captcha.setGenerator(new MathGenerator());
        }
        // 将 captcha 写入到 session 中, 目的是为了进行验证码的 校验
        session.setAttribute(RssConst.CAPTCHA_CODE, captcha);
        captcha.write(response.getOutputStream());
    }

}
